﻿app.factory('GroceryService', ['$http', '$q', '$window', 'LoginService', function ($http, $q, $window, LoginService) {
    var loadGroceryItemsDeferred = $q.defer();
    var groceryList = [];
    var isLoaded = false;

    //Load grocery items from our /api/apiGrocery Web API route and put them in an array called groceryList
    var loadGroceryList = function () {
        $http({
            url: 'http://localhost:3010/api/apiGrocery',
            method: 'GET'
        }).success(function (data) {
            groceryList.length = 0;
            groceryList = data;
            isLoaded = true;
            loadGroceryItemsDeferred.resolve(groceryList);
        }).error(function (data) {
            loadGroceryItemsDeferred.reject(data);
        });
    };

    //Add a callback function to be invoked once someone logs out of the system.
    LoginService.registerLogOutCallback(function () {
        isLoaded = false;
    });

    //Get grocery items from the promise created and resolved from the loadGroceryList function
    var getGroceryList = function () {
        if (!isLoaded) {
            loadGroceryItemsDeferred = $q.defer();
            loadGroceryList();
        }   
       
        return loadGroceryItemsDeferred.promise;
    }

    //Set the purchase date property for the given grocery item via our /api/apiGrocery Web API route
    var purchaseItem = function (item) {
        var deferred = $q.defer();

        $http({
            url: 'http://localhost:3010/api/apiGrocery/' + item.groceryItemId,
            method: 'PATCH'
        }).success(function (data) {
            item.datePurchased = data;
            deferred.resolve();
        }).error(function () {
            deferred.reject();
        });

        return deferred.promise;
    }

    //Add a new grocery item via our /api/apiGrocery Web API route
    var addItem = function (item) {
        var deferred = $q.defer();

        $http({
            url: 'http://localhost:3010/api/apiGrocery/',
            method: 'POST',
            data: item
        }).success(function (data) {
            groceryList.push(data);
            deferred.resolve();
        }).error(function () {
            deferred.reject();
        });

        return deferred.promise;
    };

    var getGroceryItemTypes = function () {
        var deferred = $q.defer();

        $http({
            url: 'http://localhost:3010/api/apiGroceryItemTypes',
            method: 'GET'
        }).success(function (data) {
            deferred.resolve(data);
        });

        return deferred.promise;
    }

    //Return an object with only the methods we want exposed to the consumor of our GroceryService
    return {
        getGroceryList: getGroceryList,
        purchaseItem: purchaseItem,
        addItem: addItem,
        getGroceryItemTypes: getGroceryItemTypes
    };
}]);